package com.alipay.rebate.shop.scheduler.productimport;

import com.alipay.rebate.shop.dao.mapper.ProductMapper;
import com.alipay.rebate.shop.scheduler.CustomFunction;
import com.alipay.rebate.shop.utils.DateUtil;
import java.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//@Component
public class ProductScheduler {

  private Logger logger = LoggerFactory.getLogger(ProductScheduler.class);

  @Autowired
  private ProductImporter productImporter;
  @Resource
  private ProductMapper productMapper;

//  @Scheduled(fixedRate = 1000 * 60 * 60)
//  public void importAllProducts() {
//    productImporter.importAllProduct();
//  }

  /**
   * 每10分钟删除过期商品
   */
  @Scheduled(fixedRate = 1000 * 60 * 10)
  public void deleteProducts() {
    CustomFunction customFunction = (r1, r2, r3, r4) ->{
      productImporter.getStaleProduct(r1, r2, r3, r4);
    };
    doBusiness(customFunction);
  }

  /**
   * 每30分钟导入新商品
   */
  @Scheduled(fixedRate = 1000 * 60 * 30)
  public void pullProduct() {

    CustomFunction customFunction = (r1,r2,r3,r4) ->{
      productImporter.pullProduct(r1, r2, r3, r4);
    };
    doBusiness(customFunction);

  }
  @Scheduled(cron = "0 0 */4 * * ?")
  public void importAllDataokeGoodsFriendsCircle(){
    productMapper.deleteDataokeGoodsFriendsCircle();
    productImporter.importAllDataokeGoodsFriendsCircle();
  }

  /**
   * 每小时30分更新商品数据
   */
  @Scheduled(cron = "0 30 * ? * *")
  public void updateProducts() {
    String date  = DateUtil.getTwentyMinutesBeforeFromNow();
    logger.debug("date is :{}",date);
    productImporter.getNewestProduct();
  }

  private void doBusiness(CustomFunction customFunction){

    LocalDateTime now = LocalDateTime.now();
    String lastHourStartTime = DateUtil.getLastHourStartTime(now);
    String nextHourStartTime = DateUtil.getNextHourStartTime(now);
    logger.debug("lastHourStartTime and nextHourStartTime is :{},{}"
        ,lastHourStartTime,nextHourStartTime);

    int hour = now.getHour();
    String startHour = String.valueOf(hour);
    String endHour = String.valueOf(hour);
    if(hour != 0){
      startHour = String.valueOf(hour - 1);
    }
    logger.debug("startHour and endHour is :{},{}"
        ,startHour,endHour);

    customFunction.doBusiness(lastHourStartTime,nextHourStartTime,startHour,endHour);

  }

}
